package com.ywb.order.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author ywb
 */

@Component
public class CustomLoadBalancer implements LoadBalancer{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement(int instanceCount){
        int current;
        int next;
        do{
            current = atomicInteger.get();
            next = (current + 1 )% instanceCount;
        }while (!atomicInteger.compareAndSet(current, next));
        return atomicInteger.get();
    }

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> instances) {
        return instances.get(getAndIncrement(instances.size()));
    }
}
